import { prisma } from '../db/prisma';

export class CleanupService {
  private static isRunning = false;

  /**
   * 清理没有客户经理维护的客户
   */
  static async cleanupUnmanagedClients() {
    if (this.isRunning) {
      console.log('清理任务已在运行中，跳过本次执行');
      return;
    }

    this.isRunning = true;
    const startTime = Date.now();

    try {
      console.log('开始执行客户清理任务...');

      // 查找所有没有分配客户经理的客户
      const unmanagedClients = await prisma.client.findMany({
        where: {
          managerAssignments: {
            none: {}
          }
        },
        select: {
          id: true,
          clientCode: true,
          clientName: true,
          createdAt: true,
          _count: {
            select: {
              serviceAssignments: true,
              workLogs: true
            }
          }
        }
      });

      if (unmanagedClients.length === 0) {
        console.log('没有发现无人维护的客户');
        return { deleted: 0, message: '没有发现无人维护的客户' };
      }

      console.log(`发现 ${unmanagedClients.length} 个无人维护的客户：`);
      unmanagedClients.forEach(client => {
        console.log(`- 客户: ${client.clientName} (${client.clientCode}), 服务分配: ${client._count.serviceAssignments}, 工作日志: ${client._count.workLogs}`);
      });

      // 批量删除这些客户（级联删除相关数据）
      const clientIds = unmanagedClients.map(client => client.id);
      
      const deleteResult = await prisma.client.deleteMany({
        where: {
          id: {
            in: clientIds
          }
        }
      });

      const executionTime = Date.now() - startTime;
      const message = `成功删除 ${deleteResult.count} 个无人维护的客户，耗时 ${executionTime}ms`;
      
      console.log(message);
      
      return {
        deleted: deleteResult.count,
        clients: unmanagedClients.map(client => ({
          id: client.id,
          clientCode: client.clientCode,
          clientName: client.clientName,
          serviceAssignments: client._count.serviceAssignments,
          workLogs: client._count.workLogs
        })),
        message,
        executionTime
      };

    } catch (error) {
      const executionTime = Date.now() - startTime;
      console.error('客户清理任务执行失败:', error);
      
      return {
        deleted: 0,
        error: error instanceof Error ? error.message : '未知错误',
        message: '客户清理任务执行失败',
        executionTime
      };
    } finally {
      this.isRunning = false;
    }
  }

  /**
   * 启动定时清理任务（每5分钟执行一次）
   */
  static startCleanupTimer() {
    console.log('启动客户自动清理定时器，每5分钟执行一次');
    
    // 立即执行一次
    this.cleanupUnmanagedClients();
    
    // 设置定时器，每5分钟（300000毫秒）执行一次
    const intervalId = setInterval(() => {
      this.cleanupUnmanagedClients();
    }, 5 * 60 * 1000);

    return intervalId;
  }

  /**
   * 停止定时清理任务
   */
  static stopCleanupTimer(intervalId: NodeJS.Timeout) {
    console.log('停止客户自动清理定时器');
    clearInterval(intervalId);
  }

  /**
   * 获取当前无人维护的客户统计信息（不删除）
   */
  static async getUnmanagedClientsStats() {
    try {
      const unmanagedClients = await prisma.client.findMany({
        where: {
          managerAssignments: {
            none: {}
          }
        },
        select: {
          id: true,
          clientCode: true,
          clientName: true,
          marketType: true,
          terminalType: true,
          createdAt: true,
          _count: {
            select: {
              serviceAssignments: true,
              workLogs: true
            }
          }
        },
        orderBy: {
          createdAt: 'desc'
        }
      });

      return {
        total: unmanagedClients.length,
        clients: unmanagedClients.map(client => ({
          id: client.id,
          clientCode: client.clientCode,
          clientName: client.clientName,
          marketType: client.marketType,
          terminalType: client.terminalType,
          createdAt: client.createdAt,
          serviceAssignments: client._count.serviceAssignments,
          workLogs: client._count.workLogs
        }))
      };
    } catch (error) {
      console.error('获取无人维护客户统计失败:', error);
      return {
        total: 0,
        clients: [],
        error: error instanceof Error ? error.message : '未知错误'
      };
    }
  }
}